const request = require('request');
const querystring = require('querystring');
const WXBizDataCrypt = appRequire('common/wx/WXBizDataCrypt');

const wxConfig = appRequire('config');

module.exports = {
    getMiniOpenId,
    decryptData
};

async function getMiniOpenId(req) {
    return new Promise((resolve, reject) => {
        let postData = req.body
        var code = postData.code
        let appId = wxConfig['wxMini' + postData.source].appId
        let secret = wxConfig['wxMini' + postData.source].secret

        console.log(appId, secret)

        var data = {
            'appid': appId,
            'secret': secret,
            'js_code': code,
            'grant_type': 'authorization_code'
        };
        var content = querystring.stringify(data);
        var url = 'https://api.weixin.qq.com/sns/jscode2session?' + content;
        request.get({
            'url': url
        }, (error, res, body) => {
            console.log(body)
            let abody = JSON.parse(body);
            resolve(abody)
        })
    })
}


async function decryptData(req) {
    let postData = req.body

    var result = await getMiniOpenId(req)
    let sessionKey = result.session_key
    var encryptedData = postData.encryptedData
    var iv = postData.iv
    let appId = wxConfig['wxMini' + postData.source].appId
    let secret = wxConfig['wxMini' + postData.source].secret

    var pc = new WXBizDataCrypt(appId, sessionKey)

    var data = await pc.decryptData(encryptedData, iv)
    return data
}